package com.comba.patch.tool.controller;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.comba.patch.tool.Bootstrap;
import com.comba.patch.tool.service.PatchOverviewService;
import com.comba.patch.tool.service.ProgressListener;
import com.comba.patch.tool.utils.AlertUtils;
import com.comba.patch.tool.utils.PatchUtils;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.stage.DirectoryChooser;

public class PatchOverviewController implements Initializable {
	private static final Logger LOGGER = LoggerFactory.getLogger(PatchOverviewController.class);
	private PatchOverviewService patchOverviewService = new PatchOverviewService();

	@FXML
	private ProgressBar progressBar;
	@FXML
	private Label progressLabel;
	@FXML
	private TextField originalDirField;
	@FXML
	private TextField currentDirField;
	@FXML
	private TextField patchDirField;
	@FXML
	private Button makingButton;

	public void selectOriginalDir() {
		DirectoryChooser chooser = new DirectoryChooser();
		File originalDir = chooser.showDialog(Bootstrap.getInstance().getPrimaryStage());
		if(originalDir != null) {
			this.originalDirField.setText(originalDir.getPath());
		}
	}
	public void selectCurrentDir() {
		DirectoryChooser chooser = new DirectoryChooser();
		File currentDir = chooser.showDialog(Bootstrap.getInstance().getPrimaryStage());
		if(currentDir != null) {
			this.currentDirField.setText(currentDir.getPath());
		}
	}
	public void selectPatchDir() {
		DirectoryChooser chooser = new DirectoryChooser();
		File patchDir = chooser.showDialog(Bootstrap.getInstance().getPrimaryStage());
		if(patchDir != null) {
			this.patchDirField.setText(patchDir.getPath());
		}
	}

	public void handleOriginalClick(MouseEvent mouseEvent) {
		int clickCount = mouseEvent.getClickCount();
		if(clickCount > 1 && mouseEvent.getButton()==MouseButton.PRIMARY) {
			this.selectOriginalDir();
		}
	}
	public void handleCurrentClick(MouseEvent mouseEvent) {
		int clickCount = mouseEvent.getClickCount();
		if(clickCount > 1 && mouseEvent.getButton()==MouseButton.PRIMARY) {
			this.selectCurrentDir();
		}
	}
	public void handlePatchClick(MouseEvent mouseEvent) {
		int clickCount = mouseEvent.getClickCount();
		if(clickCount > 1 && mouseEvent.getButton()==MouseButton.PRIMARY) {
			this.selectPatchDir();
		}
	}

	public void making() {
		if(this.validateSelectedDirs()) {
			this.makingButton.setDisable(true);
			this.progressBar.setProgress(0);
			try {
				this.patchOverviewService.making(
						new File(this.originalDirField.getText()),
						new File(this.currentDirField.getText()),
						new File(this.patchDirField.getText()), new ProgressListener() {

							@Override
							public void onProgress(int total, int current) {
								Platform.runLater(() -> {
									PatchOverviewController.this.progressBar
										.setProgress(PatchUtils.formatDouble(current * 1.0 / total));
									PatchOverviewController.this.progressLabel.setText(String.valueOf(current * 100 / total) + "%");
								});
							}

							@Override
							public void onException(int total, int current, Throwable e) {
								Platform.runLater(() -> {
									PatchOverviewController.this.progressBar
										.setProgress(PatchUtils.formatDouble(current * 1.0 / total));
									String msg = "补丁包制作失败";
									LOGGER.error(msg, e);
									AlertUtils.exception(msg, e);
								});
							}

							@Override
							public void onComplete() {
								/**
								 * 更新application线程需要放置在Platform.runLater中，否则可能抛出：
								 * Not on FX application thread; currentThread = *异常
								 */
								Platform.runLater(() -> {
									PatchOverviewController.this.progressLabel.setText("100%");
									AlertUtils.information("补丁包制作成功");
								});

							}
						});
			} catch (IOException e) {
				String msg = "补丁包制作失败";
				LOGGER.error(msg, e);
				AlertUtils.exception(msg, e);
			}
			this.makingButton.setDisable(false);
		}
	}


	private boolean validateSelectedDirs() {
		String originalDir = this.originalDirField.getText();
		if(StringUtils.isBlank(originalDir)) {
			AlertUtils.error("请选择原目录");
			return false;
		}
		if(!new File(originalDir).exists()) {
			AlertUtils.error(String.format("目录:%s不存在", originalDir));
			return false;
		}
		String currentDir = this.currentDirField.getText();
		if(StringUtils.isBlank(currentDir)) {
			AlertUtils.error("请选择现目录");
			return false;
		}
		if(!new File(currentDir).exists()) {
			AlertUtils.error(String.format("目录:%s不存在", currentDir));
			return false;
		}
		String patchDir = this.patchDirField.getText();
		if(StringUtils.isBlank(patchDir)) {
			AlertUtils.error("请选择补丁输出目录");
			return false;
		}
		return true;
	}

	@Override
	public void initialize(URL location, ResourceBundle resources) {

	}


}
